package com.roper.yygh.cmn.service.impl;

import com.alibaba.excel.EasyExcel;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.roper.yygh.cmn.listener.DictListener;
import com.roper.yygh.cmn.mapper.DictMapper;
import com.roper.yygh.cmn.service.DictService;
import com.roper.yygh.model.cmn.Dict;
import com.roper.yygh.vo.cmn.DictEeVo;
import org.springframework.beans.BeanUtils;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

/**
 * Description: 数据字典service 实现类
 * Date:      2021/12/30 19:18
 * author:    LPH
 * version:   V1.0
 */
@Service
public class DictServiceImpl extends ServiceImpl<DictMapper, Dict> implements DictService {

    // 根据id查询所有的子节点
    @Override
    @Cacheable(value = "dict", keyGenerator = "keyGenerator")
    public List<Dict> findChildData(Long id) {
        QueryWrapper<Dict> wrapper = new QueryWrapper<>();
        wrapper.eq("parent_id", id);
        List<Dict> dicts = baseMapper.selectList(wrapper);
        // 把list中的值全遍历，然后根据dict的id 去查询是否还有子节点 再set到list集合中
        for(Dict dict : dicts) {
            boolean children = isChildren(dict.getId());
            dict.setHasChildren(children);
        }
        return dicts;
    }

    // 导出数据字典接口
    @Override
    public void exportDictData(HttpServletResponse response) {
        response.setContentType("application/vnd.ms-excel");
        response.setCharacterEncoding("utf-8");

        String fileName = "dict";
        // 设置下载
        response.setHeader("Content-disposition", "attachment;filename="+fileName + ".xlsx");
        // 查询数据库
        List<Dict> dicts = baseMapper.selectList(null);

        // 把Dict 修改为DictVo
        List<DictEeVo> dictEeVoList = new ArrayList<>();
        for(Dict dict : dicts) {
            DictEeVo dictEeVo = new DictEeVo();
            // 相当于dictEeVo.setId(dict.getId());
            BeanUtils.copyProperties(dict, dictEeVo);
            dictEeVoList.add(dictEeVo);
        }

        // 调用方法直接
        try {
            EasyExcel.write(response.getOutputStream(), DictEeVo.class).sheet("dict")
                    .doWrite(dictEeVoList);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    @Override
    public void importData(MultipartFile file) {
        try {
            EasyExcel.read(file.getInputStream(), DictEeVo.class, new DictListener(baseMapper)).sheet()
                .doRead();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    // 判断id下是否有子节点
    private boolean isChildren(Long id) {
        QueryWrapper<Dict> wrapper = new QueryWrapper<>();
        wrapper.eq("parent_id", id);
        Integer count = baseMapper.selectCount(wrapper);
        // 如果count是0 0>0 返回false 如果count是1 1>0 返回true
        return count > 0;
    }

    @Override
    public String getName(String dictCode, String value) {
        // 如果dictCode为空，则直接为value查询
        if(StringUtils.isEmpty(dictCode)) {
            // 直接根据value查询
            QueryWrapper<Dict> queryWrapper = new QueryWrapper<>();
            queryWrapper.eq("value", value);
            Dict dict = baseMapper.selectOne(queryWrapper);
            return dict.getName();
        }else {
            // 根据dictCode 进行查询出id
            Dict dictByDictCode = this.getDictByDictCode(dictCode);
            Long parentId = dictByDictCode.getId();
            // 根据parentId和Value值进行查询
            QueryWrapper<Dict> queryWrapper = new QueryWrapper<>();
            queryWrapper.eq("parent_id", parentId).eq("value", value);
            Dict dict = baseMapper.selectOne(queryWrapper);
            return dict.getName();
        }
    }

    @Override
    public List<Dict> findByDictCode(String dictCode) {
        // 根据dictCode 获取id
        Dict dictByDictCode = this.getDictByDictCode(dictCode);
        // 再根据id 获取
        return this.findChildData(dictByDictCode.getId());
    }

    // 根据dictCode 获取dict对象
    private Dict getDictByDictCode(String dictCode) {
        QueryWrapper<Dict> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("dict_code", dictCode);
        return baseMapper.selectOne(queryWrapper);
    }
}
